<?php

namespace App\Console\Commands;

use App\Message;
use App\Room;
use App\RoomJoin;
use App\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use phpDocumentor\Reflection\Types\Null_;

class Swoole extends Command
{

    const ON_LINE = 1;
    const OFF_LINE = 0;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole:action {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'swoole command';

    /**
     * Swoole constructor.
     * @param Message $message
     * @param User $user
     * @param RoomJoin $room
     */
//    public function __construct(Message $message, User $user, RoomJoin $room)
//    {
//        parent::__construct();
//        $this->message = $message;
//        $this->user = $user;
//        $this->room = $room;
//    }
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $action = $this->argument('action');
        switch ($action) {
            case 'start':
                $this->start();
                break;
            case 'stop':
                $this->stop();
                break;
            case 'restart':
                $this->restart();
                break;
        }
    }

    /**
     * 开启websocket
     */
    private function start()
    {
        $data = [];

        //$data['url'] = 'http://chat.kuaile173.com/api/websocketinit';
        $data['url'] = env('APP_URL').'/api/websocketinit';
        $this->requestWesocket($data);

        $key = "zoMitkHUWrVgz9nd";//服务端请求秘钥
        $handler = \App::makeWith('App\handlers\SwooleHandler',[$this->message,$this->user,$this->room]);//new SwooleHandler();
        $ws = new \swoole_websocket_server(config('swoole.host'), config('swoole.port'));

        //服务端请求更新数据，这里是http方式
        $ws->on('request', function ($req, $respone) use($ws, $handler, $key) {
            print_r($req->post);
            if(count($req->post)){ //判断下是否有数据

                $data = $req->post;
                if( $key == $data['key']){
                    //////////////////////
                    /// 业务接口调用
                    ///////////////////////

                    $room_keyname =  $data['room_keyname'];
                    $user_id = $data['uid'];
                    $type = $data['type'];
                    if ($type == 'join') {
                        $message = $data['userinfo'];
                        $handler->sendAll($ws, $room_keyname, $user_id,$message,$type);
                    }else if ($type == 'order') {
                        $message = $data['order'];
                        $handler->sendAll($ws, $room_keyname, $user_id,$message,$type);
                    }

                    $respone->end("success");
                }else{
                    $respone->end("key error");
                }
            }
        });
        $ws->on('open',  [$handler, 'onOpen']);
        //监听WebSocket消息事件
        $ws->on('message',  [$handler, 'onMessage']);
        $ws->on('close',  [$handler, 'onClose']);
        $ws->start();
    }

    /**
     * 停止websocket
     */
    private function stop()
    {

    }

    /**
     * 重启
     */
    private function restart()
    {

    }
    private function requestWesocket($data) {
        $data['key'] = 'zoMitkHUWrVgz9nd';
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $data['url']); // 要访问的地址
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作
        return $res;
    }
}
